using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using LetLord.Models;
using LetLord.ViewModels;
using System.IO;

namespace LetLord.Controllers
{
    public class LandlordsController : Controller
    {
        private readonly LetLordContext db;
		private readonly ILandlordRepository landlordRepository;
        private readonly IResidentialPropertyRepository resPropRepository;
        private readonly IAddressRepository addressRepository;
        private readonly IReferencePhotoRepository refPhotoRepository;

		// If you are using Dependency Injection, you can delete the following constructor
        public LandlordsController() : this(new LandlordRepository(), new ResidentialPropertyRepository(), new AddressRepository(), new ReferencePhotoRepository())
        {
        }

        public LandlordsController(ILandlordRepository landlordRepository, IResidentialPropertyRepository resPropRepository, IAddressRepository addressRepository, IReferencePhotoRepository refPhotoRepository)
        {
            this.db = new LetLordContext();
			this.landlordRepository = landlordRepository;
            this.resPropRepository = resPropRepository;
            this.addressRepository = addressRepository;
            this.refPhotoRepository = refPhotoRepository;
        }

        // GET: /Landlords/Profile

        public ActionResult Profile()
        {
            return View(landlordRepository.GetLoggedInLandlord());
        }

        //
        // GET: /Landlords/LandlordDetails
        
        [HttpGet]
        public ActionResult LandlordDetails()
        {
            try
            {
                return PartialView("_EditLandlordDetailsPartial");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e);
            }
            return View("Error");
        }

        //
        // POST: /Landlords/EditLandlordDetails

        [HttpPost]
        public ActionResult EditLandlordDetails(EditLandlordDetailsViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var currentLandlord = landlordRepository.GetLoggedInLandlord();
                    currentLandlord.FirstName = viewModel.FirstName;
                    currentLandlord.LastName = viewModel.LastName;
                    currentLandlord.Email = viewModel.Email;
                    landlordRepository.InsertOrUpdate(currentLandlord);
                    landlordRepository.Save();

                    return PartialView("_LandlordDetailsPartial");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e);
                }
            }
            return PartialView("_LandlordDetailsPartial");
        }

        //
        // GET: /Landlords/GetLandlordProperties

        [HttpGet]
        public ActionResult GetLandlordProperties()
        {
            try
            {
                return PartialView("_LandlordPropertiesPartial");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e);
            }
            return View("Error");
        }

        //
        // GET: /Landlords/LandlordProperties

        [HttpGet]
        public ActionResult LandlordProperties()
        {
            try
            {
                return PartialView("_CreatePropertyPartial");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e);
            }
            return View("Error");
        }

        //
        // POST: /Landlords/CreateProperty

        [HttpPost]
        public ActionResult CreateProperty(CreatePropertyViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var newProperty = new ResidentialProperty();
                    newProperty.Address = new Address();

                    newProperty.Address.Line1       = viewModel.Line1;
                    newProperty.Address.Line2       = viewModel.Line2;
                    newProperty.Address.TownCity    = viewModel.TownCity;
                    newProperty.Address.County      = viewModel.County;
                    newProperty.Address.PostCode    = viewModel.PostCode;

                    newProperty.PropertyTypeString      = viewModel.PropertyTypeString;
                    newProperty.SizeSquareMeters        = viewModel.SizeSquareMeters;
                    newProperty.NumberOfBedrooms        = viewModel.NumberOfBedrooms;
                    newProperty.NumberOfBathrooms       = viewModel.NumberOfBathrooms;
                    newProperty.NumberOfReceptionRooms  = viewModel.NumberOfReceptionRooms;
                    newProperty.Description             = viewModel.Description;
                    newProperty.HasBackGarden           = viewModel.HasBackGarden;
                    newProperty.HasFrontGarden          = viewModel.HasFrontGarden;
                    newProperty.HasSecureParking        = viewModel.HasSecureParking;
                    newProperty.IsDisabledFriendly      = viewModel.IsDisabledFriendly;
                    //decimal monthlyRate = decimal.Parse(viewModel.MonthlyRate);
                    newProperty.MonthlyRate             = viewModel.MonthlyRate;
                    newProperty.DateAdded               = DateTime.Now.Date;

                    newProperty.UserId = landlordRepository.GetLoggedInLandlord().UserId;
                    newProperty.AddressId = newProperty.ResidentialPropertyId;

                    resPropRepository.InsertOrUpdate(newProperty);
                    //addressRepository.InsertOrUpdate(newProperty.Address);
                    resPropRepository.Save();
                    //addressRepository.Save();
 
                    return PartialView("_LandlordPropertiesPartial", landlordRepository.GetLoggedInLandlord());

                    //return Json(new { error = false, message = "New property added"});
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message + "\n" + e.InnerException);
                }
            }
            return View("Error");
        }

        // GET: /Landlords/DeleteProperty
        [HttpGet]
        public ActionResult DeleteProperty(int id)
        {
            return View(resPropRepository.Find(id));
        }

        // POST: /Landlords/DeleteProperty
        [HttpPost, ActionName("DeleteProperty")]
        public ActionResult DeletePropertyConfirm(int id)
        {
            try
            {
                resPropRepository.Delete(id);
                resPropRepository.Save();
                return PartialView("_LandlordPropertiesPartial", landlordRepository.GetLoggedInLandlord());
            }
            catch (Exception e)
            {
                e.InnerException.ToString();
            }
            return View("Error");
        }

        // GET: /Landlords/UploadPropertyPhoto
        [HttpGet]
        public ActionResult UploadPropertyPhoto(int id)
        {
            try
            {
                var viewModel = new UploadPropertyPhotoViewModel();
                viewModel.Id = id;
                return PartialView("_UploadPropertyPhotoPartial", viewModel);
            }
            catch (Exception e)
            {
                e.InnerException.ToString();
            }
            return View("Error");
        }

        // POST: /Landlords/UploadPropertyPhoto
        [HttpPost]
        public ActionResult UploadPropertyPhoto(HttpPostedFileBase fileData, Landlord landlord, UploadPropertyPhotoViewModel viewModel)
        {
            if (fileData != null)
            {
                try
                {
                    var supportedTypes = new[] { "jpg", "jpeg", "png", "JPG", "JPEG", "PNG" };
                    var fileExt = System.IO.Path.GetExtension(fileData.FileName).Substring(1);

                    if (!supportedTypes.Contains(fileExt))
                    {
                        ModelState.AddModelError("photo", "Invalid type. Only the following types (jpg, jpeg, png) are supported.");
                        return View();
                    }

                    using (var db = new LetLordContext())
                    {
                        var propertyPhoto = new PropertyPhoto();
                        // Convert HttpPostedFileBase to byte array
                        MemoryStream target = new MemoryStream();
                        fileData.InputStream.CopyTo(target);
                        byte[] photo = target.ToArray();

                        propertyPhoto.ResidentialPropertyId = viewModel.Id;
                        propertyPhoto.File = photo;
                        propertyPhoto.Format = fileExt;
                        propertyPhoto.DateUploaded = DateTime.Now.Date;
                        propertyPhoto.Name = "";
                        propertyPhoto.Description = "";

                        db.Image.Add(propertyPhoto);
                        db.SaveChanges();

                        return RedirectToAction("Profile");
                    }
                }
                catch (Exception e)
                {
                    e.InnerException.ToString();
                }
            }
            return View("Error");
        }

        [HttpGet]
        public ActionResult GetPhotos(int id)
        {
            PropertyPhoto photo = new PropertyPhoto();
            photo.File = landlordRepository.GetPropertyPhoto(id);
            var format = db.Image.SingleOrDefault(x => x.ImageId == id).Format;
            if (photo == null)
            {
                return View("Error");
            }
            return File(photo.File, format);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing) {
                landlordRepository.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

